﻿#include <stdio.h>
#include <Windows.h>

BYTE OldCode[12] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
BYTE HookCode[12] = { 0x48, 0xB8, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0xFF, 0xE0 };
DWORD_PTR base;

typedef int (WINAPI* TrueMessageBoxW)(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType);

TrueMessageBoxW mbx = NULL;

int WINAPI MyMessageBoxW(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
    return mbx(hWnd, L"Hooked Message!", lpCaption, uType);
}

int main(int argc, char* argv[])
{
    HMODULE hwnd = GetModuleHandle(TEXT("user32.dll"));
    DWORD_PTR base = (DWORD_PTR)GetProcAddress(hwnd, "MessageBoxW");
    DWORD OldProtect;

    if (VirtualProtect((LPVOID)base, 12, PAGE_EXECUTE_READWRITE, &OldProtect))
    {
        mbx = MessageBoxW;
        memcpy(OldCode, (LPVOID)base, 12);                  // 拷贝原始机器码指令
        mbx = (TrueMessageBoxW)VirtualAlloc(NULL, 12, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
        //memcpy(mbx, &OldCode[0], 12);

        *(PINT64)(HookCode + 2) = (INT64)&MyMessageBoxW;    // 填充90为指定跳转地址
    }
    memcpy((LPVOID)base, &HookCode, sizeof(HookCode));      // 拷贝Hook机器指令

    MessageBoxW(NULL, L"hello lyshark", NULL, NULL);

    return 0;
}
